<?php
/**
 * 用于客服聊天系统，提供当前用户状态
 */

define('IN_ECS', TRUE);

include '../../includes/init.php';

$act = $_GET['act'];

if ($act === 'getUserInfo') {
	$resp = array('code' => 0);
	if (isset($_COOKIE['ECS']) && isset($_COOKIE['ECS']['user_id']) && $_COOKIE['ECS']['user_id'] > 0) {
		$arr = $_COOKIE['ECS'];
		if (isset($arr['username']) && isset($arr['user_id'])) {
			$resp['code'] = 1;
			$resp['username'] = $arr['username'];
			$resp['user_id'] = $arr['user_id'];
			$resp['role'] = 1; // TODO 现无用户角色
			$resp['join_id'] = 'u_'.md5($arr['username']); //作为socket的通话id
		}
	}

	if (!isset($resp['user_id'])) {
		$resp = createTempAccount();
	}

	$resp['ip'] = real_ip();
	$resp['access_time'] = time();
	echo json_encode($resp);
	exit;
}

elseif($act === 'test') {
	echo '<pre>';

	var_dump($_COOKIE);
	$tempaccount = html_entity_decode($_COOKIE['tempaccount']);
	$arr = unserialize($tempaccount);
	var_dump($arr);
	echo '<br/>';

	var_dump($_SESSION);
	echo '</pre>';

	exit('<br/>exit;');
}

function createTempAccount()
{
	$arr = array();

	if ($_COOKIE['tempaccount'] !== NULL && isset($_COOKIE['tempaccount'])) {
		$tempaccount = html_entity_decode($_COOKIE['tempaccount']);
		$arr = unserialize($tempaccount);
	}

	if (!(is_array($arr) && isset($arr['username']))) {
		$arr['code'] = 1;
		$arr['username'] = uniqid('u');
		$arr['user_id'] = 0;
		$arr['role'] = 0;
		$arr['join_id'] = 'u_'.md5($arr['username']);

		$tempaccount = htmlentities(serialize($arr));
		setcookie('tempaccount', $tempaccount, time() + 3600 * 24 * 30, '/');
	}

	return $arr;
}